﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net.Sockets;
using rkShared.Net;
using rkShared.BEncode;

namespace rkServer
{
    public partial class ServerForm : Form
    {
        private GameServer m_server;
        private ServerLogic m_serverLogic;
        private ChatServer m_chatserver;

        public ServerForm()
        {
            InitializeComponent();
        }

        void m_serverLogic_ClientHit(ClientInfo client)
        {
            textBox1.Invoke(new EventHandler(delegate
            {
                textBox1.AppendText(string.Format("\r\n{0} has been hit.", client.NickName));
            }));
        }
        void m_server_ClientEnteredGame(ClientInfo cliInfo, NetMessage msg)
        {
            textBox1.Invoke(new EventHandler(delegate
            {
                textBox1.AppendText(cliInfo.NickName + " entered the game.\r\n");
            }));
        }
        void m_chatserver_ChatMessageReceived(ClientInfo client, NetMessage msg)
        {
            textBox1.Invoke(new EventHandler(delegate
            {
                textBox1.AppendText("\r\n" + (msg.Data as BEncodedString).ToUnicodeString());
            }));
        }
        void m_server_clientRegistered(rkShared.Net.ClientInfo cliInfo)
        {
            textBox1.Invoke(new EventHandler(delegate
                {
                    textBox1.AppendText(cliInfo.NickName + " registered.\r\n");
                }));
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            FrmServerSettings _settingsForm = new FrmServerSettings();
            _settingsForm.StartPosition = FormStartPosition.CenterParent;
            if (_settingsForm.ShowDialog(this) == DialogResult.OK)
            {
                m_server = new GameServer(_settingsForm.Port);
                m_chatserver = new ChatServer(m_server);
                m_server.ClientRegistered += new ClientRegisteredEventHandler(m_server_clientRegistered);
                m_server.ClientEnteredGame += new ClientEnteredGameEventHandler(m_server_ClientEnteredGame);

                m_chatserver.ChatMessageReceived += new MessageReceivedEventHandler(m_chatserver_ChatMessageReceived);
                m_serverLogic = new ServerLogic(m_server, _settingsForm.GameName, _settingsForm.Seed);
                m_serverLogic.ClientHit += new ServerLogic.GameInfoEventHandler(m_serverLogic_ClientHit);
            }
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
        }
        private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_serverLogic != null)
                m_serverLogic.EndServer();
        }
    }
}